package org.nanotek.tika.io;

import java.nio.file.Files;
import java.util.Date;

import org.apache.tika.Tika;
import org.apache.tika.detect.Detector;
import org.apache.tika.io.TikaInputStream;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.mime.MediaType;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.Parser;
import org.apache.tika.parser.PasswordProvider;
import org.nanotek.tika.MediaDetail;
import org.nanotek.tika.MediaDetectionException;
import org.nanotek.tika.MediaDetector;

public class TikaMediaDetector implements MediaDetector<TikaInputStream>{

	private Metadata md; 
	private Detector detector; 
	private Parser parser;
	private Tika tika;
	
	public TikaMediaDetector() {
		tika = new Tika();
	}

	public TikaMediaDetector(Metadata md) {
		this.md = md;
	}

	
	public TikaMediaDetector(Metadata md, Detector detector) {
		super();
		this.md = md;
		this.detector = detector;
		tika = new Tika (detector);
	}

	public TikaMediaDetector(Detector detector, Parser parser) {
		super();
		this.detector = detector;
		this.parser = parser;
		tika = new Tika (detector,parser);
	}

	public TikaMediaDetector(Metadata md, Detector detector, Parser parser) {
		super();
		this.md = md;
		this.detector = detector;
		this.parser = parser;
		tika = new Tika (detector,parser);
	}

	public  MediaDetail detectMediaType(TikaInputStream input) throws MediaDetectionException {

		try { 
			String url  = input.getFile().toString();
			md = new Metadata();
			ParseContext context = new ParseContext();
			context.set(Parser.class, parser);
			context.set(PasswordProvider.class, new PasswordProvider() {
				public String getPassword(Metadata metadata) {
					String password = "";
					return password ;
				}
			});
			MediaType mediaType = detector.detect(input, md);
			MediaDetail mediaDetails = new MediaDetail();
			mediaDetails.setLocation(url);
			mediaDetails.setDateUpdate(new Date());
			mediaDetails.setSize(Files.size(input.getFile().toPath()));
			mediaDetails.setContentType(mediaType.toString());
			String outString =  tika.parseToString(input);
//			Reader reader = tika.parse(input, md);
//			TextField field = new TextField("TextField", reader);
			mediaDetails.setTikaStringContent(outString);
			return mediaDetails;
		}catch (Exception ex){ 
				throw new MediaDetectionException(ex);
		}
	}

	public Detector getDetector() {
		return detector;
	}

	public void setDetector(Detector detector) {
		this.detector = detector;
	}

	public Parser getParser() {
		return parser;
	}

	public void setParser(Parser parser) {
		this.parser = parser;
	}
}
